package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BaseException;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.service.ShoppingCartService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONStringer;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;


@Slf4j
@Service
@AllArgsConstructor
public class ShoppingServiceImpl implements ShoppingCartService {

    private SetmealService setmealService;
    private DishService dishService;
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加商品到购物车
     * @param shoppingCartDTO 购物车商品信息
     */
    @Transactional
    public void addToCart(ShoppingCartDTO shoppingCartDTO) {
        Long userId = BaseContext.getCurrentId();
        log.info("调用添加购物车接口,用户id:{},商品信息:{}", userId, shoppingCartDTO);
        // 用户购物车已有商品进行数量加一处理
        ShoppingCart existingItem = findExistingCartItem(shoppingCartDTO, userId);
        
        if (existingItem != null) {
            // 进行数量加一处理
            existingItem.setNumber(existingItem.getNumber() + 1);
            // 更新数量
            shoppingCartMapper.update(existingItem);
            log.info("更新购物车商品成功,用户id{},更新数据:{}", userId, existingItem);
        } else {
            // 根据DTO获取商品信息并构建购物车对象
            ShoppingCart shoppingCart = buildShoppingCart(shoppingCartDTO,userId);

            // 插入数据库
            shoppingCartMapper.insert(shoppingCart);
            log.info("添加购物车商品成功,用户id{}，购物车信息{}", userId, shoppingCart);
        }

    }

    /**
     * 清空购物车所有商品
     */
    @Override
    public void cleanShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
    }

    /**
     * 查看客户端购物车商品
     * @return
     */
    @Override
    public List<ShoppingCart> showShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        return shoppingCartMapper.selectByUserId(userId);
    }

    /**
     * 减少购物车指定商品数量(数量归零移除该项)
     * @param shoppingCartDTO 减少购物车商品消息
     */
    @Override
    @Transactional
    public void reduceShoppingCartItem(ShoppingCartDTO shoppingCartDTO) {
        Long userId = BaseContext.getCurrentId();

        // 构建查询条件
        ShoppingCart queryCriteria = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, queryCriteria);
        queryCriteria.setUserId(userId);

        // 获取匹配的购物车商品项
        List<ShoppingCart> list =  shoppingCartMapper.selectList(queryCriteria);

        if(list.isEmpty()){
            return; // 无商品直接返回
        }

        // 待减少的购物车项
        ShoppingCart targetItem = list.get(0);
        Integer updateNumber = targetItem.getNumber() - 1;

        if (updateNumber < 1) {
            // 清空该项商品
            shoppingCartMapper.deleteById(targetItem.getId());
        } else {
            // 减去商品数量
            targetItem.setNumber(updateNumber);
            shoppingCartMapper.update(targetItem);
        }


    }

    /**
     * 查询购物车已存在的商品
     * @param dto 购物车商品信息
     * @param userId 用户id
     * @return 购物车对象
     */
    private ShoppingCart findExistingCartItem(ShoppingCartDTO dto, Long userId) {
        return shoppingCartMapper.selectByUserIdWithDishIdOrSetmealId(dto, userId);
    }


    /**
     * 构建购物车对象
     * @param shoppingCartDTO 购物车商品信息
     * @param userId 用户ID
     * @return 购物车对象
     */
    private ShoppingCart buildShoppingCart(ShoppingCartDTO shoppingCartDTO,Long userId){
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .number(1)
                .createTime(LocalDateTime.now())
                .dishFlavor(shoppingCartDTO.getDishFlavor())
                .build();

        if (shoppingCartDTO.getSetmealId() != null) {
            // 处理套餐
            Setmeal setmeal = setmealService.getById(shoppingCartDTO.getSetmealId());
            shoppingCart.setSetmealId(setmeal.getId());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setAmount(setmeal.getPrice());
        } else {
            // 处理菜单
            Dish dish = dishService.getById(shoppingCartDTO.getDishId());
            shoppingCart.setDishId(dish.getId());
            shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setName(dish.getName());
        }

        return shoppingCart;
    }
}
